//数据库运行命令nodemon
var express = require('express');
var router = express.Router();
const { loginModel, videosModel, dataModel, errorsModel } = require('../db/db')


/* GET home page. */
router.get('/', async function (req, res, next) {

});

router.post('/login', async (req, res) => {
 
    let body = req.body;
    
 
    let data = await loginModel.find(body);

    res.send({
      code: 200,
      data
    });
  })

router.get('/vlist', async function (req, res, next) {
  try {
    const videoList = await videosModel.find();
    res.send({
      code: 200,
      videoList
    });
  } catch (error) {
    console.error('获取视频列表失败:', error);
    await logError('Backend', 'DatabaseError', '获取视频列表失败', `错误详情: ${error.message}, 堆栈: ${error.stack}`);
    res.status(500).send({ code: 500, message: '获取视频列表服务器错误' });
  }
})

/**
 * 记录错误日志到数据库
 * @param {string} source 错误来源
 * @param {string} errorType 错误类型
 * @param {string} errorTitle 错误标题
 * @param {string} errorDescription 错误描述
 */
async function logError(source, errorType, errorTitle, errorDescription) {
  try {
    await errorsModel.create({
      source,
      errorType,
      fieldType: errorType, // 使用errorType作为fieldType的默认值
      errorTitle,
      errorDescription,
      errorTime: new Date()
    });
    console.log('错误日志已记录:', { source, errorType, errorTitle });
  } catch (logErr) {
    console.error('记录错误日志失败:', logErr);
  }
}

/**
 * 视频编辑接口 - 处理点赞和收藏操作
 * 当点赞或收藏总数变化达到1000的倍数时才向客户端发送socket更新事件
 * 支持增加（正数count）和减少（负数count）操作
 */
router.post('/vEdit', async function (req, res, next) {
  try {
    const io = req.app.get('io');
    const { videoId, action, count } = req.body;
    
    // 参数验证
    if (!videoId || !action || count === undefined) {
      await logError('Backend', 'ValidationError', 'vEdit参数验证失败', `缺少必要参数: videoId=${videoId}, action=${action}, count=${count}`);
      return res.status(400).send({ code: 400, message: '参数不完整' });
    }
    
    const video = await videosModel.findOne({ id: videoId });

    if (!video) {
      await logError('Backend', 'NotFoundError', '视频不存在', `视频ID ${videoId} 在数据库中未找到`);
      return res.status(404).send({ code: 404, message: '视频不存在' });
    }

    let shouldEmitUpdate = false;

    if (action === 'like') {
      // 记录操作前的点赞数
      const previousLikes = video.likes || 0;
      
      // 更新点赞数，确保不为负数
      video.likes = Math.max(0, previousLikes + count);
      const newLikes = video.likes;
      
      // 判断点赞总数是否跨越了1000的倍数边界
      const previousThousands = Math.floor(previousLikes / 1000);
      const newThousands = Math.floor(newLikes / 1000);
      
      if (previousThousands !== newThousands) {
        shouldEmitUpdate = true;
        console.log(`点赞数从 ${previousLikes} 变化到 ${newLikes}，跨越1000倍数边界，发送socket更新`);
      }
    } else if (action === 'favorite') {
      // 记录操作前的收藏数
      const previousFavorites = video.favorites || 0;
      
      // 更新收藏数，确保不为负数
      video.favorites = Math.max(0, previousFavorites + count);
      const newFavorites = video.favorites;
      
      // 判断收藏总数是否跨越了1000的倍数边界
      const previousThousands = Math.floor(previousFavorites / 1000);
      const newThousands = Math.floor(newFavorites / 1000);
      
      if (previousThousands !== newThousands) {
        shouldEmitUpdate = true;
        console.log(`收藏数从 ${previousFavorites} 变化到 ${newFavorites}，跨越1000倍数边界，发送socket更新`);
      }
    } else {
      await logError('Backend', 'ValidationError', '无效的操作类型', `不支持的action类型: ${action}`);
      return res.status(400).send({ code: 400, message: '无效的操作类型' });
    }
    
    await video.save();
    
    // 只有满足条件时才发送socket更新事件
    if (shouldEmitUpdate) {
      io.emit('dataUpdate');
      console.log('已发送数据更新事件');
    } else {
      console.log('数据变化未跨越1000倍数边界，不发送socket更新');
    }

    res.send({ code: 200 });
  } catch (error) {
    console.error('更新失败:', error);
    await logError('Backend', 'DatabaseError', 'vEdit数据库操作失败', `错误详情: ${error.message}, 堆栈: ${error.stack}`);
    res.status(500).send({ code: 500, message: '服务器错误' });
  }
});


router.get('/get', async (req, res) => {
  try {
    let sj = await dataModel.find();
    res.send({ code: 200, sj });
  } catch (error) {
    console.error('获取数据失败:', error);
    await logError('Backend', 'DatabaseError', '获取数据失败', `错误详情: ${error.message}, 堆栈: ${error.stack}`);
    res.status(500).send({ code: 500, message: '获取数据服务器错误' });
  }
})


router.get('/sc', async (req, res) => {
  try {
    if (!req.query.id) {
      await logError('Backend', 'ValidationError', '删除数据参数验证失败', '缺少必要参数: id');
      return res.status(400).send({ code: 400, message: '缺少id参数' });
    }
    
    await dataModel.deleteOne({ _id: req.query.id });
    res.send({ code: 200 });
  } catch (error) {
    console.error('删除数据失败:', error);
    await logError('Backend', 'DatabaseError', '删除数据失败', `错误详情: ${error.message}, 堆栈: ${error.stack}`);
    res.status(500).send({ code: 500, message: '删除数据服务器错误' });
  }
})

router.post('/add', async (req, res) => {
  try {
    if (!req.body || Object.keys(req.body).length === 0) {
      await logError('Backend', 'ValidationError', '添加数据参数验证失败', '请求体为空');
      return res.status(400).send({ code: 400, message: '请求体不能为空' });
    }
    
    await dataModel.create(req.body);
    res.send({ code: 200 });
  } catch (error) {
    console.error('添加数据失败:', error);
    await logError('Backend', 'DatabaseError', '添加数据失败', `错误详情: ${error.message}, 堆栈: ${error.stack}`);
    res.status(500).send({ code: 500, message: '添加数据服务器错误' });
  }
})


router.post('/gx', async (req, res) => {
  try {
    let { _id } = req.body;
    
    if (!_id) {
      await logError('Backend', 'ValidationError', '更新数据参数验证失败', '缺少必要参数: _id');
      return res.status(400).send({ code: 400, message: '缺少_id参数' });
    }
    
    console.log(req.body);
    await dataModel.updateOne({ _id }, req.body);
    res.send({ code: 200 });
  } catch (error) {
    console.error('更新数据失败:', error);
    await logError('Backend', 'DatabaseError', '更新数据失败', `错误详情: ${error.message}, 堆栈: ${error.stack}`);
    res.status(500).send({ code: 500, message: '更新数据服务器错误' });
  }
})
// 错误日志记录接口
router.post('/logError', async (req, res) => {
  try {
    const { source, errorType, fieldType, title, description, timestamp } = req.body;
    
    // 参数验证
    if (!source || !errorType || !fieldType || !title || !description) {
      return res.status(400).send({ code: 400, message: '缺少必要的错误日志参数' });
    }
    
    // 创建错误日志记录
    await errorsModel.create({
      errorTime: timestamp || `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`,
      errorType,
      fieldType,
      errorTitle: title,
      errorDescription: description,
      source: source || 'Unknown'
    });
    
    console.log(`[错误日志] ${source} - ${errorType}: ${title}`);
    res.send({ code: 200, message: '错误日志记录成功' });
  } catch (error) {
    console.error('记录错误日志失败:', error);
    res.status(500).send({ code: 500, message: '记录错误日志失败' });
  }
});

module.exports = router;
